package servlets;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringEscapeUtils;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.KeyFactory;

import domain.Utilisateur;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet{
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		//String content = req.getParameter("content");
		String email = StringEscapeUtils.escapeHtml3(req.getParameter("email"));
		String password = DigestUtils.sha1Hex(StringEscapeUtils.escapeHtml3(req.getParameter("password")));
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        try {
        	Entity user = datastore.get(KeyFactory.createKey(Utilisateur.class.getSimpleName(), email));
        	if(user.getProperty("password").equals(password)){
                HttpSession s = req.getSession(true);
        		s.setAttribute("email", email);
        	}
        } catch(EntityNotFoundException e){
        }
        resp.sendRedirect("/accueil.html");
	}
}
